home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 3 / Amiga Format CD03 (1996-07-04)(Future Publishing)(GB)(Track 1 of 6)[!][issue 1996-08].iso / comms / netsoftware / archie38_1.lha / archie-1.4 / getopt.c < prev    next >
C/C++ Source or Header  |  1995-01-04  |  19KB  |  676 lines

  1. /* Getopt for GNU.
  2.    NOTE: getopt is now part of the C library, so if you don't know what
  3.    "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
  4.    before changing it!
  5.  
  6.    Copyright (C) 1987, 88, 89, 90, 91, 1992 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify it
  9.    under the terms of the GNU Library General Public License as published
  10.    by the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU Library General Public
  19.    License along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* AIX requires this to be the first thing in the file. */
  23. #ifdef __GNUC__
  24. #define alloca __builtin_alloca
  25. #else /* not __GNUC__ */
  26. #if defined (HAVE_ALLOCA_H) || (defined(sparc) && (defined(sun) || (!defined(USG) && !defined(SVR4) && !defined(__svr4__))))
  27. #include <alloca.h>
  28. #else
  29. #ifdef _AIX
  30.  #pragma alloca
  31. #else
  32. char *alloca ();
  33. #endif
  34. #endif /* alloca.h */
  35. #endif /* not __GNUC__ */
  36.  
  37. #include <stdio.h>
  38.  
  39. /* This needs to come after some library #include
  40.    to get __GNU_LIBRARY__ defined.  */
  41. #ifdef    __GNU_LIBRARY__
  42. #undef    alloca
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #else    /* Not GNU C library.  */
  46. #define    __alloca    alloca
  47. #endif    /* GNU C library.  */
  48.  
  49.  
  50. #ifndef __STDC__
  51. #define const
  52. #endif
  53.  
  54. /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
  55.    long-named option.  Because this is not POSIX.2 compliant, it is
  56.    being phased out. */
  57. #undef GETOPT_COMPAT
  58.  
  59. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  60.    but it behaves differently for the user, since it allows the user
  61.    to intersperse the options with the other arguments.
  62.  
  63.    As `getopt' works, it permutes the elements of ARGV so that,
  64.    when it is done, all the options precede everything else.  Thus
  65.    all application programs are extended to handle flexible argument order.
  66.  
  67.    Setting the environment variable POSIXLY_CORRECT disables permutation.
  68.    Then the behavior is completely standard.
  69.  
  70.    GNU application programs can use a third alternative mode in which
  71.    they can distinguish the relative order of options and other arguments.  */
  72.  
  73. #include "getopt.h"
  74.  
  75. /* For communication from `getopt' to the caller.
  76.    When `getopt' finds an option that takes an argument,
  77.    the argument value is returned here.
  78.    Also, when `ordering' is RETURN_IN_ORDER,
  79.    each non-option ARGV-element is returned here.  */
  80.  
  81. char *optarg = 0;
  82.  
  83. /* Index in ARGV of the next element to be scanned.
  84.    This is used for communication to and from the caller
  85.    and for communication between successive calls to `getopt'.
  86.  
  87.    On entry to `getopt', zero means this is the first call; initialize.
  88.  
  89.    When `getopt' returns EOF, this is the index of the first of the
  90.    non-option elements that the caller should itself scan.
  91.  
  92.    Otherwise, `optind' communicates from one call to the next
  93.    how much of ARGV has been scanned so far.  */
  94.  
  95. int optind = 0;
  96.  
  97. /* The next char to be scanned in the option-element
  98.    in which the last option character we returned was found.
  99.    This allows us to pick up the scan where we left off.
  100.  
  101.    If this is zero, or a null string, it means resume the scan
  102.    by advancing to the next ARGV-element.  */
  103.  
  104. static char *nextchar;
  105.  
  106. /* Callers store zero here to inhibit the error message
  107.    for unrecognized options.  */
  108.  
  109. int opterr = 1;
  110.  
  111. /* Describe how to deal with options that follow non-option ARGV-elements.
  112.  
  113.    If the caller did not specify anything,
  114.    the default is REQUIRE_ORDER if the environment variable
  115.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  116.  
  117.    REQUIRE_ORDER means don't recognize them as options;
  118.    stop option processing when the first non-option is seen.
  119.    This is what Unix does.
  120.    This mode of operation is selected by either setting the environment
  121.    variable POSIXLY_CORRECT, or using `+' as the first character
  122.    of the list of option characters.
  123.  
  124.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  125.    so that eventually all the non-options are at the end.  This allows options
  126.    to be given in any order, even with programs that were not written to
  127.    expect this.
  128.  
  129.    RETURN_IN_ORDER is an option available to programs that were written
  130.    to expect options and other ARGV-elements in any order and that care about
  131.    the ordering of the two.  We describe each non-option ARGV-element
  132.    as if it were the argument of an option with character code 1.
  133.    Using `-' as the first character of the list of option characters
  134.    selects this mode of operation.
  135.  
  136.    The special argument `--' forces an end of option-scanning regardless
  137.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  138.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  139.  
  140. static enum
  141. {
  142.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  143. } ordering;
  144.  
  145. #ifdef    __GNU_LIBRARY__
  146. #include <string.h>
  147. #define    my_index    strchr
  148. #define    my_bcopy(src, dst, n)    memcpy ((dst), (src), (n))
  149. #else
  150.  
  151. /* Avoid depending on library functions or files
  152.    whose names are inconsistent.  */
  153.  
  154. char *getenv ();
  155.  
  156. static char *
  157. my_index (string, chr)
  158.      const char *string;
  159.      int chr;
  160. {
  161.   while (*string)
  162.     {
  163.       if (*string == chr)
  164.     return (char *) string;
  165.       string++;
  166.     }
  167.   return 0;
  168. }
  169.  
  170. static void
  171. my_bcopy (from, to, size)
  172.      char *from, *to;
  173.      int size;
  174. {
  175.   int i;
  176.   for (i = 0; i < size; i++)
  177.     to[i] = from[i];
  178. }
  179. #endif                /* GNU C library.  */
  180.  
  181. /* Handle permutation of arguments.  */
  182.  
  183. /* Describe the part of ARGV that contains non-options that have
  184.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  185.    `last_nonopt' is the index after the last of them.  */
  186.  
  187. static int first_nonopt;
  188. static int last_nonopt;
  189.  
  190. /* Exchange two adjacent subsequences of ARGV.
  191.    One subsequence is elements [first_nonopt,last_nonopt)
  192.    which contains all the non-options that have been skipped so far.
  193.    The other is elements [last_nonopt,optind), which contains all
  194.    the options processed since those non-options were skipped.
  195.  
  196.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  197.    the new indices of the non-options in ARGV after they are moved.  */
  198.  
  199. static void
  200. exchange (argv)
  201.      char **argv;
  202. {
  203.   int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
  204.   char **temp = (char **) __alloca (nonopts_size);
  205.  
  206.   /* Interchange the two blocks of data in ARGV.  */
  207.  
  208.   my_bcopy ((char *)&argv[first_nonopt], (char *)temp,
  209.         nonopts_size);
  210.   my_bcopy ((char *)&argv[last_nonopt], (char *)&argv[first_nonopt],
  211.         (optind - last_nonopt) * sizeof (char *));
  212.   my_bcopy ((char *)temp, (char *)&argv[first_nonopt + optind - last_nonopt],
  213.             nonopts_size);
  214.  
  215.   /* Update records for the slots the non-options now occupy.  */
  216.  
  217.   first_nonopt += (optind - last_nonopt);
  218.   last_nonopt = optind;
  219. }
  220.  
  221. /* Scan elements of ARGV (whose length is ARGC) for option characters
  222.    given in OPTSTRING.
  223.  
  224.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  225.    then it is an option element.  The characters of this element
  226.    (aside from the initial '-') are option characters.  If `getopt'
  227.    is called repeatedly, it returns successively each of the option characters
  228.    from each of the option elements.
  229.  
  230.    If `getopt' finds another option character, it returns that character,
  231.    updating `optind' and `nextchar' so that the next call to `getopt' can
  232.    resume the scan with the following option character or ARGV-element.
  233.  
  234.    If there are no more option characters, `getopt' returns `EOF'.
  235.    Then `optind' is the index in ARGV of the first ARGV-element
  236.    that is not an option.  (The ARGV-elements have been permuted
  237.    so that those that are not options now come last.)
  238.  
  239.    OPTSTRING is a string containing the legitimate option characters.
  240.    If an option character is seen that is not listed in OPTSTRING,
  241.    return '?' after printing an error message.  If you set `opterr' to
  242.    zero, the error message is suppressed but we still return '?'.
  243.  
  244.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  245.    so the following text in the same ARGV-element, or the text of the following
  246.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  247.    wants an optional arg; if there is text in the current ARGV-element,
  248.    it is returned in `optarg', otherwise `optarg' is set to zero.
  249.  
  250.    If OPTSTRING starts with `-' or `+', it requests different methods of
  251.    handling the non-option ARGV-elements.
  252.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  253.  
  254.    Long-named options begin with `--' instead of `-'.
  255.    Their names may be abbreviated as long as the abbreviation is unique
  256.    or is an exact match for some defined option.  If they have an
  257.    argument, it follows the option name in the same ARGV-element, separated
  258.    from the option name by a `=', or else the in next ARGV-element.
  259.    When `getopt' finds a long-named option, it returns 0 if that option's
  260.    `flag' field is nonzero, the value of the option's `val' field
  261.    if the `flag' field is zero.
  262.  
  263.    The elements of ARGV aren't really const, because we permute them.
  264.    But we pretend they're const in the prototype to be compatible
  265.    with other systems.
  266.  
  267.    LONGOPTS is a vector of `struct option' terminated by an
  268.    element containing a name which is zero.
  269.  
  270.    LONGIND returns the index in LONGOPT of the long-named option found.
  271.    It is only valid when a long-named option has been found by the most
  272.    recent call.
  273.  
  274.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  275.    long-named options.  */
  276.  
  277. int
  278. _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
  279.      int argc;
  280.      char *const *argv;
  281.      const char *optstring;
  282.      const struct option *longopts;
  283.      int *longind;
  284.      int long_only;
  285. {
  286.   int option_index;
  287.  
  288.   optarg = 0;
  289.  
  290.   /* Initialize the internal data when the first call is made.
  291.      Start processing options with ARGV-element 1 (since ARGV-element 0
  292.      is the program name); the sequence of previously skipped
  293.      non-option ARGV-elements is empty.  */
  294.  
  295.   if (optind == 0)
  296.     {
  297.       first_nonopt = last_nonopt = optind = 1;
  298.  
  299.       nextchar = NULL;
  300.  
  301.       /* Determine how to handle the ordering of options and nonoptions.  */
  302.  
  303.       if (optstring[0] == '-')
  304.     {
  305.       ordering = RETURN_IN_ORDER;
  306.       ++optstring;
  307.     }
  308.       else if (optstring[0] == '+')
  309.     {
  310.       ordering = REQUIRE_ORDER;
  311.       ++optstring;
  312.     }
  313.       else if (getenv ("POSIXLY_CORRECT") != NULL)
  314.     ordering = REQUIRE_ORDER;
  315.       else
  316.     ordering = PERMUTE;
  317.     }
  318.  
  319.   if (nextchar == NULL || *nextchar == '\0')
  320.     {
  321.       if (ordering == PERMUTE)
  322.     {
  323.       /* If we have just processed some options following some non-options,
  324.          exchange them so that the options come first.  */
  325.  
  326.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  327.         exchange ((char **) argv);
  328.       else if (last_nonopt != optind)
  329.         first_nonopt = optind;
  330.  
  331.       /* Now skip any additional non-options
  332.          and extend the range of non-options previously skipped.  */
  333.  
  334.       while (optind < argc
  335.          && (argv[optind][0] != '-' || argv[optind][1] == '\0')
  336. #ifdef GETOPT_COMPAT
  337.          && (longopts == NULL
  338.              || argv[optind][0] != '+' || argv[optind][1] == '\0')
  339. #endif                /* GETOPT_COMPAT */
  340.          )
  341.         optind++;
  342.       last_nonopt = optind;
  343.     }
  344.  
  345.       /* Special ARGV-element `--' means premature end of options.
  346.      Skip it like a null option,
  347.      then exchange with previous non-options as if it were an option,
  348.      then skip everything else like a non-option.  */
  349.  
  350.       if (optind != argc && !strcmp (argv[optind], "--"))
  351.     {
  352.       optind++;
  353.  
  354.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  355.         exchange ((char **) argv);
  356.       else if (first_nonopt == last_nonopt)
  357.         first_nonopt = optind;
  358.       last_nonopt = argc;
  359.  
  360.       optind = argc;
  361.     }
  362.  
  363.       /* If we have done all the ARGV-elements, stop the scan
  364.      and back over any non-options that we skipped and permuted.  */
  365.  
  366.       if (optind == argc)
  367.     {
  368.       /* Set the next-arg-index to point at the non-options
  369.          that we previously skipped, so the caller will digest them.  */
  370.       if (first_nonopt != last_nonopt)
  371.         optind = first_nonopt;
  372.       return EOF;
  373.     }
  374.  
  375.       /* If we have come to a non-option and did not permute it,
  376.      either stop the scan or describe it to the caller and pass it by.  */
  377.  
  378.       if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
  379. #ifdef GETOPT_COMPAT
  380.       && (longopts == NULL
  381.           || argv[optind][0] != '+' || argv[optind][1] == '\0')
  382. #endif                /* GETOPT_COMPAT */
  383.       )
  384.     {
  385.       if (ordering == REQUIRE_ORDER)
  386.         return EOF;
  387.       optarg = argv[optind++];
  388.       return 1;
  389.     }
  390.  
  391.       /* We have found another option-ARGV-element.
  392.      Start decoding its characters.  */
  393.  
  394.       nextchar = (argv[optind] + 1
  395.           + (longopts != NULL && argv[optind][1] == '-'));
  396.     }
  397.  
  398.   if (longopts != NULL
  399.       && ((argv[optind][0] == '-'
  400.        && (argv[optind][1] == '-' || long_only))
  401. #ifdef GETOPT_COMPAT
  402.       || argv[optind][0] == '+'
  403. #endif                /* GETOPT_COMPAT */
  404.       ))
  405.     {
  406.       const struct option *p;
  407.       char *s = nextchar;
  408.       int exact = 0;
  409.       int ambig = 0;
  410.       const struct option *pfound = NULL;
  411.       int indfound;
  412.  
  413.       while (*s && *s != '=')
  414.     s++;
  415.  
  416.       /* Test all options for either exact match or abbreviated matches.  */
  417.       for (p = longopts, option_index = 0; p->name;
  418.        p++, option_index++)
  419.     if (!strncmp (p->name, nextchar, s - nextchar))
  420.       {
  421.         if (s - nextchar == strlen (p->name))
  422.           {
  423.         /* Exact match found.  */
  424.         pfound = p;
  425.         indfound = option_index;
  426.         exact = 1;
  427.         break;
  428.           }
  429.         else if (pfound == NULL)
  430.           {
  431.         /* First nonexact match found.  */
  432.         pfound = p;
  433.         indfound = option_index;
  434.           }
  435.         else
  436.           /* Second nonexact match found.  */
  437.           ambig = 1;
  438.       }
  439.  
  440.       if (ambig && !exact)
  441.     {
  442.       if (opterr)
  443.         fprintf (stderr, "%s: option `%s' is ambiguous\n",
  444.              argv[0], argv[optind]);
  445.       nextchar += strlen (nextchar);
  446.       optind++;
  447.       return '?';
  448.     }
  449.  
  450.       if (pfound != NULL)
  451.     {
  452.       option_index = indfound;
  453.       optind++;
  454.       if (*s)
  455.         {
  456.           /* Don't test has_arg with >, because some C compilers don't
  457.          allow it to be used on enums. */
  458.           if (pfound->has_arg)
  459.         optarg = s + 1;
  460.           else
  461.         {
  462.           if (opterr)
  463.             {
  464.               if (argv[optind - 1][1] == '-')
  465.             /* --option */
  466.             fprintf (stderr,
  467.                  "%s: option `--%s' doesn't allow an argument\n",
  468.                  argv[0], pfound->name);
  469.               else
  470.             /* +option or -option */
  471.             fprintf (stderr,
  472.                  "%s: option `%c%s' doesn't allow an argument\n",
  473.                  argv[0], argv[optind - 1][0], pfound->name);
  474.             }
  475.           nextchar += strlen (nextchar);
  476.           return '?';
  477.         }
  478.         }
  479.       else if (pfound->has_arg == 1)
  480.         {
  481.           if (optind < argc)
  482.         optarg = argv[optind++];
  483.           else
  484.         {
  485.           if (opterr)
  486.             fprintf (stderr, "%s: option `%s' requires an argument\n",
  487.                  argv[0], argv[optind - 1]);
  488.           nextchar += strlen (nextchar);
  489.           return '?';
  490.         }
  491.         }
  492.       nextchar += strlen (nextchar);
  493.       if (longind != NULL)
  494.         *longind = option_index;
  495.       if (pfound->flag)
  496.         {
  497.           *(pfound->flag) = pfound->val;
  498.           return 0;
  499.         }
  500.       return pfound->val;
  501.     }
  502.       /* Can't find it as a long option.  If this is not getopt_long_only,
  503.      or the option starts with '--' or is not a valid short
  504.      option, then it's an error.
  505.      Otherwise interpret it as a short option. */
  506.       if (!long_only || argv[optind][1] == '-'
  507. #ifdef GETOPT_COMPAT
  508.       || argv[optind][0] == '+'
  509. #endif                /* GETOPT_COMPAT */
  510.       || my_index (optstring, *nextchar) == NULL)
  511.     {
  512.       if (opterr)
  513.         {
  514.           if (argv[optind][1] == '-')
  515.         /* --option */
  516.         fprintf (stderr, "%s: unrecognized option `--%s'\n",
  517.              argv[0], nextchar);
  518.           else
  519.         /* +option or -option */
  520.         fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  521.              argv[0], argv[optind][0], nextchar);
  522.         }
  523.       nextchar = (char *) "";
  524.       optind++;
  525.       return '?';
  526.     }
  527.     }
  528.  
  529.   /* Look at and handle the next option-character.  */
  530.  
  531.   {
  532.     char c = *nextchar++;
  533.     char *temp = my_index (optstring, c);
  534.  
  535.     /* Increment `optind' when we start to process its last character.  */
  536.     if (*nextchar == '\0')
  537.       ++optind;
  538.  
  539.     if (temp == NULL || c == ':')
  540.       {
  541.     if (opterr)
  542.       {
  543.         if (c < 040 || c >= 0177)
  544.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  545.                argv[0], c);
  546.         else
  547.           fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
  548.       }
  549.     return '?';
  550.       }
  551.     if (temp[1] == ':')
  552.       {
  553.     if (temp[2] == ':')
  554.       {
  555.         /* This is an option that accepts an argument optionally.  */
  556.         if (*nextchar != '\0')
  557.           {
  558.         optarg = nextchar;
  559.         optind++;
  560.           }
  561.         else
  562.           optarg = 0;
  563.         nextchar = NULL;
  564.       }
  565.     else
  566.       {
  567.         /* This is an option that requires an argument.  */
  568.         if (*nextchar != '\0')
  569.           {
  570.         optarg = nextchar;
  571.         /* If we end this ARGV-element by taking the rest as an arg,
  572.            we must advance to the next element now.  */
  573.         optind++;
  574.           }
  575.         else if (optind == argc)
  576.           {
  577.         if (opterr)
  578.           fprintf (stderr, "%s: option `-%c' requires an argument\n",
  579.                argv[0], c);
  580.         c = '?';
  581.           }
  582.         else
  583.           /* We already incremented `optind' once;
  584.          increment it again when taking next ARGV-elt as argument.  */
  585.           optarg = argv[optind++];
  586.         nextchar = NULL;
  587.       }
  588.       }
  589.     return c;
  590.   }
  591. }
  592.  
  593. int
  594. getopt (argc, argv, optstring)
  595.      int argc;
  596.      char *const *argv;
  597.      const char *optstring;
  598. {
  599.   return _getopt_internal (argc, argv, optstring,
  600.                (const struct option *) 0,
  601.                (int *) 0,
  602.                0);
  603. }
  604.  
  605. #ifdef TEST
  606.  
  607. /* Compile with -DTEST to make an executable for use in testing
  608.    the above definition of `getopt'.  */
  609.  
  610. int
  611. main (argc, argv)
  612.      int argc;
  613.      char **argv;
  614. {
  615.   int c;
  616.   int digit_optind = 0;
  617.  
  618.   while (1)
  619.     {
  620.       int this_option_optind = optind ? optind : 1;
  621.  
  622.       c = getopt (argc, argv, "abc:d:0123456789");
  623.       if (c == EOF)
  624.     break;
  625.  
  626.       switch (c)
  627.     {
  628.     case '0':
  629.     case '1':
  630.     case '2':
  631.     case '3':
  632.     case '4':
  633.     case '5':
  634.     case '6':
  635.     case '7':
  636.     case '8':
  637.     case '9':
  638.       if (digit_optind != 0 && digit_optind != this_option_optind)
  639.         printf ("digits occur in two different argv-elements.\n");
  640.       digit_optind = this_option_optind;
  641.       printf ("option %c\n", c);
  642.       break;
  643.  
  644.     case 'a':
  645.       printf ("option a\n");
  646.       break;
  647.  
  648.     case 'b':
  649.       printf ("option b\n");
  650.       break;
  651.  
  652.     case 'c':
  653.       printf ("option c with value `%s'\n", optarg);
  654.       break;
  655.  
  656.     case '?':
  657.       break;
  658.  
  659.     default:
  660.       printf ("?? getopt returned character code 0%o ??\n", c);
  661.     }
  662.     }
  663.  
  664.   if (optind < argc)
  665.     {
  666.       printf ("non-option ARGV-elements: ");
  667.       while (optind < argc)
  668.     printf ("%s ", argv[optind++]);
  669.       printf ("\n");
  670.     }
  671.  
  672.   exit (0);
  673. }
  674.  
  675. #endif /* TEST */
  676.